{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "x_data = np.random.rand(100).astype(np.float32)\n",
    "y_data = x_data*0.1 + 0.3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
    "#create tensorflow structure start#\n",
    "\n",
    "#定义参数形状和初始化方式\n",
    "Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0))\n",
    "biases = tf.Variable(tf.zeros([1]))\n",
    "y_predicted = Weights*x_data + biases\n",
    "\n",
    "#定义loss function\n",
    "loss = tf.reduce_mean(tf.square(y_predicted - y_data))\n",
    "#指定优化器及学习率\n",
    "optimizer = tf.train.GradientDescentOptimizer(0.5)\n",
    "#为优化器指定要最小化的loss function\n",
    "train = optimizer.minimize(loss)\n",
    "\n",
    "init = tf.global_variables_initializer()\n",
    "\n",
    "#create tensorflow structure end#"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 [0.45422357] [0.1395873]\n",
      "20 [0.18330543] [0.25355506]\n",
      "40 [0.12050435] [0.2885683]\n",
      "60 [0.10504685] [0.29718626]\n",
      "80 [0.10124221] [0.29930744]\n",
      "100 [0.10030576] [0.29982954]\n",
      "120 [0.10007527] [0.29995805]\n",
      "140 [0.10001854] [0.29998967]\n",
      "160 [0.10000455] [0.29999748]\n",
      "180 [0.10000111] [0.2999994]\n",
      "200 [0.10000027] [0.29999986]\n"
     ]
    }
   ],
   "source": [
    "# open a session of tensorflow\n",
    "with tf.Session() as sess:\n",
    "    sess.run(init)\n",
    "    for step in range(201):\n",
    "        #开始训练模型，每run一次，tensorflow执行一次\n",
    "        sess.run(train)\n",
    "        if step % 20 == 0:\n",
    "            # sess.run(Weights)获取当前参数的值\n",
    "            print(step,sess.run(Weights),sess.run(biases))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
